import json
# shell命令行开启（进入shell环境）
# python manage.py runserver
from django.shortcuts import render
from django.http import HttpResponse
from shop import models
from django.http import JsonResponse
# Create your views here.
import top.api
import http.client
# 这里填写你申请到的APPkey

# 配置阿里SDK
appkey = '25541421'
secret = '04ede9704b4da9fd2d13eecd3b37e60d'
url = 'gw.api.taobao.com'
port = 80

# 首页商品渠道链接      // 0精选 9660  1女装 9658  2美妆 9653 3鞋包 9648 4美食 9649 5家电 9656 6母婴 9650 7家居 9655 8男装 9654 9运动户外 9651
def initchannellist(request):
    material_id=request.GET.get('material_id', '9660')
    okdict = {'title', 'pict_url', 'item_description','item_id','user_type','coupon_amount','volume','zk_final_price'}
    req = top.api.TbkDgOptimusMaterialRequest(url, port)
    req.set_app_info(top.appinfo(appkey, secret))
    req.page_size = 100
    req.adzone_id = 80892900374
    req.page_no = 1
    req.material_id = material_id
    # req.device_value = "xxx"
    # req.device_encrypt = "MD5"
    # req.device_type = "IMEI"
    # req.content_id = 323
    # req.content_source = "xxx"
    try:
        respdict = req.getResponse()
        print(type(respdict))
        # print(resp)
        print(type(JsonResponse(respdict)))
        # abc=respdict["tbk_dg_optimus_material_response"]["result_list"]["map_data"]
        # print("abc",type(abc))
        # whq_dict_list(解析目标字典模板,待解析字典)
        listresp=whq_dict_list(okdict,respdict)
        # print(type(listresp))
        # print(listresp)
        jsongoods = {'response':''}
        jsongoods['response']=listresp
        print(jsongoods)
        return JsonResponse(jsongoods, safe=False)
    except Exception as e:
        print(e)
        return JsonResponse({"msg": "service error!!"})

# 商品详情处理taobao.tbk.item.info.get
def iteminfoget(request):
    itemid=request.GET.get('item_id', '566352261884')
    ip=request.GET.get('ip','11.22.33.43')
    req = top.api.TbkItemInfoGetRequest(url, port)
    req.set_app_info(top.appinfo(appkey, secret))
    # 566352261884
    req.num_iids = itemid
    req.platform = 1
    req.ip = ip
    try:
        resp = req.getResponse()
        print(resp)
        return JsonResponse(resp, safe=False)
    except Exception as e:
        print(e)

# 好券清单API（导购）只能搜索有券,搜索类目商品，自动高佣金
def getHaoQuan_list_items(request):
    material_id=request.GET.get('material_id', '9660')
    req = top.api.TbkDgOptimusMaterialRequest(url, port)
    req.set_app_info(top.appinfo(appkey, secret))
    req.page_size = 100
    req.adzone_id = 80892900374
    req.page_no = 1
    req.material_id = material_id
    try:
        respdict = req.getResponse()
        return JsonResponse(respdict, safe=False)
    except Exception as e:
        print(e)
        return JsonResponse({"msg": "service error!!"})


def getyuanshenglistjson(request):
    # json定义接口：jsondict{'uid':'',}

    okdict = {'title', 'pict_url', 'item_description','item_id','user_type','coupon_amount','volume','zk_final_price'}
    req = top.api.TbkDgOptimusMaterialRequest(url, port)
    req.set_app_info(top.appinfo(appkey, secret))
    req.page_size = 100
    req.adzone_id = 80892900374
    req.page_no = 1
    req.material_id = 9660
    # req.device_value = "xxx"
    # req.device_encrypt = "MD5"
    # req.device_type = "IMEI"
    # req.content_id = 323
    # req.content_source = "xxx"
    try:
        respdict = req.getResponse()
        print(type(respdict))
        # print(resp)
        print(type(JsonResponse(respdict)))
        # abc=respdict["tbk_dg_optimus_material_response"]["result_list"]["map_data"]
        # print("abc",type(abc))
        # whq_dict_list(解析目标字典模板,待解析字典)
        listresp=whq_dict_list(okdict,respdict)
        # print(type(listresp))
        # print(listresp)
        jsongoods = {'response':''}
        jsongoods['response']=listresp
        print(jsongoods)
        return JsonResponse(jsongoods, safe=False)
    except Exception as e:
        print(e)
        return JsonResponse({"msg": "service error!!"})



def index(request):
    return render(request,'index.html')

def add(request):
    a = request.GET['a']
    b = request.GET['b']
    c = int(a)+int(b)
    return HttpResponse(str(c))

def add2(request,a,b):
    models.addPserson()
    c = int(a) + int(b)
    return HttpResponse(str(c))

# 复杂嵌套遍历模型遍历3层字典，第三层内包含数组函数模型，实用根据okdict模板要求解析返回“子字典列表”
# 传入dict是需要解析的三层原始数据，okdict是数组中每一个小dict的取值模板，最后组成oklist   样子是oklist[{},]
# by:whq

def whq_dict_list(okdict,dict):
    oklist=[]
    # 标题 图片路径 副标题 商品id 卖家类型 佣金比率 30天销量 折扣价

    # 遍历第一层字典的键值
    for key1 in dict:
        # 筛选第一层中值是字典的进入循环，否则pass
        if type(dict[key1]).__name__ == 'dict':
            # 遍历第二层字典
            # print('key1 :', key1)

            for key2 in dict[key1]:
                # 筛选第二层中值是字典的进入循环，否则pass
                if type(dict[key1][key2]).__name__ == 'dict':
                    # print('key2 :', key2)

                    # 遍历第三层
                    for key3 in dict[key1][key2]:
                        # print('key3 :', key3)
                        # print(type(dict[key1][key2][key3]))

                        for index in range(len(dict[key1][key2][key3])):
                            # print(index)
                            # print(dict[key1][key2][key3][index])
                            # 取到json第三层的数组列表，列表内是许多个重复字典，listdict就是列表中的一个字典
                            listdict=dict[key1][key2][key3][index]
                            # print("aaa=",type(listdict))
                            gooddict = {key: value for key, value in listdict.items() if key in okdict}  # 建立子字典
                            # print("其中一个字典的取值结果是",gooddict)
                            # 把字典gooddict插入到oklist列表
                            oklist.append(gooddict)
                            # del dict['Name']  # 删除键是'Name'的条目
                else:
                    pass
        else:
            pass   #过滤不是字典的键值
    # print("oklist=====",oklist)
    return oklist


def login(request):
    username=request.POST.get('username')
    password = request.POST.get('password')
    try:
        user=models.User.objects.get(name=username)
        if(user.password==password):
            print('用户正确')
            return render(request, 'index.html')
        else:
            print('用户密码错误')
    except:
        print('用户名错误')
    return render(request,'login.html')

def register(request):
    username=request.POST.get('name')
    password=request.POST.get('password')
    email=request.POST.get('email')
    sex=request.POST.get('sex')
    cake=request.POST.get('cake')
    print(username,password,email,sex,cake)
    try:
        user=models.User.objects.create(name=username,password=password,email=email,sex=sex,cake=cake)
        print('注册成功')
    except:
        print(('注册失败'))

    return render(request,'register.html')
